package org.jpro.interceptor;

import java.lang.reflect.Method;

import org.jpro.annotation.FormatResponseBodyAnnotation;
import org.jpro.common.http.ResponseVO;
import org.jpro.common.util.JsonMapper;
import org.jpro.exception.ExceptionCode;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <P>功能描述 : 统一返回结构为ResponseVO格式，方便接口管理</P>
 * <P>File name : FormatResponseBodyAdvice </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/1/1 上午12:37</P>
 */
@Order(1)
@ControllerAdvice(annotations = { Controller.class, RestController.class })
public class FormatResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        Method method = returnType.getMethod();
        FormatResponseBodyAnnotation formatResponseBodyAnnotation = method.getAnnotation(FormatResponseBodyAnnotation.class);

        // 如果没有统一格式化返回结果的注解， 那么就默认是格式化
        if (formatResponseBodyAnnotation == null) {
            return true;
        }
        return formatResponseBodyAnnotation.value();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Page) {
            Page<?> page = (Page<?>) body;
            return new ResponseVO(ExceptionCode.SUCCESS, page);
        } else if (body instanceof String) {// 如果是String 类型的话，需要自己转json，返回字符串，否则的话系统报错
            return JsonMapper.toJson(new ResponseVO(ExceptionCode.SUCCESS, body));
        } else {
            return new ResponseVO(ExceptionCode.SUCCESS, body);
        }
    }

}
